package cn.iocoder.yudao.module.engine.controller.app.gamematches;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.engine.controller.app.gamematches.vo.AppGameMatchesRespVO;
import cn.iocoder.yudao.module.engine.controller.app.gamematches.vo.AppGameMatchesSaveReqVO;
import cn.iocoder.yudao.module.resource.api.IGameMatchesApi;
import cn.iocoder.yudao.module.resource.api.model.gamematches.GameMatchesDTO;
import cn.iocoder.yudao.module.resource.api.model.gamematches.GameMatchesSaveReqDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 对局记录")
@RestController
@RequestMapping("/lm/game-matches")
@Validated
public class AppGameMatchesController {
    @Resource
    private IGameMatchesApi gameMatchesApi;

    @PostMapping("/create")
    @Operation(summary = "创建对局记录")
    @PreAuthenticated
    public CommonResult<String> createGameMatches(@Valid @RequestBody AppGameMatchesSaveReqVO createReqVO) {
        final Long userId = getLoginUserId();
        final GameMatchesSaveReqDTO req = BeanUtils.toBean(createReqVO, GameMatchesSaveReqDTO.class);
        req.setMatchId(IdUtil.objectId());
        req.setUserId(userId);
        return success(gameMatchesApi.createGameMatches(req));
    }

    @RequestMapping(path = "/finish", method = {RequestMethod.POST, RequestMethod.PUT})
    @Operation(summary = "完成对局记录")
    @PreAuthenticated
    public CommonResult<Boolean> updateGameMatches() {
        final Long userId = getLoginUserId();
        final GameMatchesSaveReqDTO req = new GameMatchesSaveReqDTO();
        req.setUserId(userId);
        req.setFinishedAt(LocalDateTime.now());
        gameMatchesApi.updateGameMatches(req);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得对局记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<AppGameMatchesRespVO> getGameMatches(@RequestParam("id") String id) {
        final Long userId = getLoginUserId();
        final GameMatchesDTO gameMatches = gameMatchesApi.getGameMatches(userId, id);
        return success(BeanUtils.toBean(gameMatches, AppGameMatchesRespVO.class));
    }

}